package com.maven.plugins.mybatis.utils;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

//import java.io.PrintStream;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.FileSystemUtils;

import com.maven.plugins.mybatis.core.Table;

import freemarker.cache.FileTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * Freemarker工具
 * 
 * @author : fredia
 * @email : trumpey@163.com
 * @since : 2017年11月23日
 * @version : v0.0.1
 */
public class FreemarkerUtils {
	private static Configuration cfg = new Configuration();

	private static PathMatchingResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();

	private static String suffix = ".ftl";

	private static String folderName = "rbj-generator";

	private static String tmpdir = System.getProperty("java.io.tmpdir") + folderName + "/";

	private static String[] templatesName = { "freemaker-domain", "freemaker-mapper", "freemaker-sqlmap",
			"freemaker-service", "freemaker-service-impl", "freemaker-vo", "freemaker-dto" };

	public static void processBefore() throws Exception {
		File tmpFile = new File(tmpdir);
		if (!tmpFile.exists()) {
			tmpFile.mkdirs();
		}
		for (String templateName : templatesName) {
			Resource resource = patternResolver.getResource("classpath:META-INF/" + templateName + suffix);

			FileCopyUtils.copy(resource.getInputStream(),
					new FileOutputStream(new File(tmpdir, templateName + suffix)));
		}

		FileTemplateLoader templateLoader = new FileTemplateLoader(new File(tmpdir));

		cfg.setTemplateLoader(templateLoader);
	}

	public static void processEnd() throws Exception {
		if (!FileSystemUtils.deleteRecursively(new File(tmpdir)))
			System.out.println("---------------删除临时文件异常-----------------");
	}

	public static String process(String templateName, Table table) throws Exception {
		Template temp = cfg.getTemplate(templateName + suffix, "utf-8");
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		temp.process(table, new OutputStreamWriter(bos));
		return bos.toString("UTF-8");
	}

	public static void write(String path, String content) throws Exception {
		File generatorFile = new File(path);
		if (generatorFile.isDirectory()) {
			throw new Exception(path + "不是一个文件");
		}
		File parentFile = generatorFile.getParentFile();
		if ((!parentFile.exists()) && (!parentFile.mkdirs())) {
			throw new Exception("文件夹创建失败");
		}
		if (generatorFile.exists()) {
			return;
		}
		FileCopyUtils.copy(content,
				new BufferedWriter(new OutputStreamWriter(new FileOutputStream(generatorFile), "UTF-8")));

		System.out.println("save:" + path);
	}

	static {
		cfg.setDefaultEncoding("UTF-8");
	}
}
